package com.quan.generator.web.controller;

import com.quan.commons.core.bean.R;
import com.quan.commons.core.core.MyBaseController;
import com.quan.commons.core.utils.PageUtils;
import com.quan.generator.service.MySQLGeneratorService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 代码生成
 */
@RestController
@RequestMapping("/generator")
public class MySQLGeneratorController extends MyBaseController {

    @Autowired
    private MySQLGeneratorService service;

    @RequestMapping("index")
    public String index() {
        return "index";
    }

    /**
     * 查询数据库
     * @param params
     * @return
     */
    @GetMapping(value = "database")
    public R database(@RequestParam Map<String, Object> params) {
        return R.ok().put("data", this.service.selectDatabase(params));
    }

    /**
     * 数据库表列表
     * @param params
     * @return
     */
    @GetMapping(value = "tables")
    public R tables(@RequestParam Map<String, Object> params) {
        return R.ok().put("data", this.service.selectTables(new PageUtils(request), params));
    }

    /**
     * 代码生成
     * @param packageName 包名 com.quan
     * @param moduleName  模块名称 ums
     * @param tables      表名：多个表用逗号”,“隔开
     * @param response
     * @throws IOException
     */
    @RequestMapping("code")
    public void code(String database, String packageName, String moduleName, String tables, HttpServletResponse response) throws IOException {
        byte[] data = this.service.generatorCode(database, packageName, moduleName, tables.split(","));

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

}
